package com.jiangnan.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.jiangnan.entity.CreditLog
import com.jiangnan.repository.CreditRepository
import kotlinx.coroutines.launch

class CreditViewModel : ViewModel() {
  private val repo = CreditRepository()

  private val _credit = MutableLiveData<Int>()
  val credit: LiveData<Int> = _credit

  private val _logs = MutableLiveData<List<CreditLog>>()
  val logs: LiveData<List<CreditLog>> = _logs

  private val _error = MutableLiveData<String>()
  val error: LiveData<String> = _error

  fun loadCredit(userId: Long) = viewModelScope.launch {
    try {
      val res = repo.getCredit(userId)
      if (res.code == 1) _credit.value = res.data ?: 0
      else _error.value = res.msg
    } catch (e: Exception) { _error.value = e.message }
  }

  fun loadLogs(userId: Long) = viewModelScope.launch {
    try {
      val res = repo.getLogs(userId)
      if (res.code == 1) _logs.value = res.data.orEmpty()
      else _error.value = res.msg
    } catch (e: Exception) { _error.value = e.message }
  }

  fun returnBook(
    userId: Long, borrowId: Long,
    borrowDate: String, returnDate: String
  ) {
    viewModelScope.launch {
      try {
        val res = repo.returnBook(userId, borrowId, borrowDate, returnDate)
        if (res.code == 1) {
          // 刷新数据
          loadCredit(userId)
          loadLogs(userId)
        } else _error.value = res.msg
      } catch (e: Exception) { e.printStackTrace() }
    }
  }
}
